<?php

namespace App\Http\Controllers\WxApi;

use App\Http\Controllers\Controller;

use App\Http\Controllers\WxApi\Handles\Event;
use App\Http\Controllers\WxApi\Handles\Text;
use App\Models\Site;
use App\Services\ModuleService;
use Houdunren\WeChat\Button;
use Houdunren\WeChat\Message;
use Houdunren\WeChat\WeChat;
use Illuminate\Http\Request;
use App\Models\WeChat as Model;
use Illuminate\Support\Facades\App;
use Log;

class ApiController extends Controller
{
    protected $handles = [
        Text::class,
        Event::class,
    ];

    public function handle(Model $model, WeChat $weChat, Message $message)
    {
        //可以存入config临时配置文件中，但是这总只能在支持config的框架中使用，所以我们也可以使用类静态遍历的方式来处理。
        // config(['houdunren.wechat' => $model]);

        $weChat->init($model);
        $this->subscribe($message,$model);
        foreach ($this->handles as $class) {
            //循环遍历每一个类，如果一个类有返回值即符合某个事件，则停止循环,使用return返回。
            $content = App::call([new $class($model, $message), 'handle']);
            if ($content) {
                return $content;
            }
        }
    }

    public function subscribe($message, $model)
    {
        $modules = ModuleService::all();
        foreach ($modules as $module) {
            if ($module['wechat']['subscribe']) {
                $class = "Modules\\{$module['name']}\\System\\Subscribe";
                app($class)->handle($message, $model);
            }

        }

    }

}
